(function ($) {
    $.fn.yqCodeEdit = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqCodeEdit.methods[opts](this, param);
        }

        $this = this;
        var opt;
        var $uniqueID;
        if ($this.data("yqtype") == "yqCodeEdit") {
            $uniqueID = $this.attr("ID");
            var opts_ = $.extend({}, options($this));
            delete opts_.editor;

            destroy($this);
            $this = $("#" + $uniqueID);
            opt = $.extend(opts_, opts);
        }
        else {
            opt = $.extend({}, $.fn.yqCodeEdit.defaults, opts);
            $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                $uniqueID = $.getUniqueID();
                $this.attr("ID", $uniqueID);
            }
        }

        opt.edit_files = [];     //选择后，未上传文件列表
        opt.html_files = [];     //原网页文件信息 + 已上传文件

        if (opt.width === undefined && $this.width() > 0) {
            opt.width = $this.width();
        }
        else if (typeof opt.width != "undefined") {
            $this.width(opt.width);
        }

        if (opt.height === undefined && $this.height() > 0) {
            opt.height = $this.height();
        }
        else if (typeof opt.height != "undefined") {
            $this.height(opt.height);
        }

        if ($this[0].tagName.toLowerCase() != "textarea") {
            var $uniqueID = $this.attr("id");
            $this.removeAttr("id");
            $this.after('<textarea id="' + $uniqueID + '" style="width: ' + opt.width + 'px;height:' + opt.height + 'px;"></textarea>')
            $this.remove();
            $this = $("#" + $uniqueID);
        }

        opt.onload = true;

        //变量信息
        $this.data("codeedit_opt", opt);
        $this.data("yqtype", "yqCodeEdit");

        opt.themes_val = {
            eclipse: {
                theme: "eclipse",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/eclipse.css", type: "css" },
                ]
            }, light: {
                theme: "xq-light",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/xq-light.css", type: "css" },
                ]
            }, day: {
                theme: "3024-day",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/3024-day.css", type: "css" },
                ]
            }, night: {
                theme: "3024-night",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/3024-night.css", type: "css" },
                ]
            }, idea: {
                theme: "idea",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/idea.css", type: "css" },
                ]
            }, twilight: {
                theme: "twilight",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/twilight.css", type: "css" },
                ]
            }
        };

        var $object = $this;

        $object.attr("readonly", "readonly");

        LoadJsCss($object, function () {
            if (opt.type == 'md') {
                init_edit_md($object);
            } else {
                init_edit($object);
            }

            opt.afterBindingTitle.call($object);
        });

        return $this;

    };

    $.fn.yqCodeEdit.defaults = {
        types: ["html", "aspx", "javascript", "css", "txt", "min", "json", "sql", "python"],
        type: null,
        value: null,
        isEdit: true,   //可编辑
        theme: "eclipse",

        themes: ["eclipse", "light", "day", "night", "idea", "twilight"],
        fontSize: 14,
        goDocEnd: true,  //加载后，显示在尾部
        // width: 400, //模态编辑器宽度 格式为 800（数字）
        // height: 300, //模态编辑器高度 格式为 600（数字）

        //--文件--------------------------------
        storageType: 3,//1-数据库存储，2-外部存储 其他-路径
        storageName: null,
        accept: "image/*",
        chunk: false,       //分片上传
        directup: false,   //直接上传（选择文件后立即上传）
        data: { files: [], code: "" },
        //---------------------------------------------

        afterBindingTitle: function () { },   //标题绑定后
        onChange: function (val) {//修改类型
            //console.log("ssssssss", val);
        },
        afterSetData: function (val) {

        }
    };

    $.fn.yqCodeEdit.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, param) {
            resize($(jq[0]), param);
        },

        setTheme: function (jq, theme) {
            setTheme($(jq[0]), theme);
        },

        openFind: function (jq) {
            var opt = options($(jq[0]));
            opt.editor.execCommand("find")
        },

        clear: function (jq, data) {
            setValue($(jq[0]), null);
        },
        setValue: function (jq, value) {
            setValue($(jq[0]), value);
        },
        getValue: function (jq) {
            return getValue($(jq[0]));
        },
        setData: function (jq, data) {
            setData($(jq[0]), data);
        },
        getData: function (jq) {
            return getData($(jq[0]));
        },
        setFontSize: function (jq, size) {
            setFontSize($(jq[0]), size);
        },
        disable: function (jq) {
            isEdit($(jq[0]), false);
        },
        enable: function (jq) {
            isEdit($(jq[0]), true);
        },
        setType: function (jq, typeval) {
            setType($(jq[0]), typeval);
        },
        getType: function (jq) {
            return getType($(jq[0]));
        },
    };

    function LoadJsCss($object, callback) {
        var opt = options($object);

        var file = [];

        if (opt.type == "md") {
            file.push({ url: "/scripts/editor.md/css/editormd.min.css", type: "css" });
            file.push({ url: "/scripts/editor.md/editormd.min.js", type: "js" });
        } else {
            file.push({ url: "/scripts/editor.md/lib/codemirror/lib/codemirror.css", type: "css" });
            file.push({ url: "/scripts/editor.md/lib/codemirror/lib/codemirror.js", type: "js" });
            //支持代码折叠/
            file.push({ url: "/scripts/editor.md/lib/codemirror/addon/fold/foldgutter.css", type: "css" });
            file.push({ url: "/scripts/editor.md/lib/codemirror/addon/fold/foldcode.js", type: "js" });
            file.push({ url: "/scripts/editor.md/lib/codemirror/addon/fold/foldgutter.js", type: "js" });
            file.push({ url: "/scripts/editor.md/lib/codemirror/addon/fold/brace-fold.js", type: "js" });
            file.push({ url: "/scripts/editor.md/lib/codemirror/addon/fold/comment-fold.js", type: "js" });
        }

        $.yqLoadJsCss(file, function () {
            callback();
        })
    }

    function options($object) {
        return $object.data("codeedit_opt");
    }

    function destroy($object) {
        var opt = options($object);
        var $uniqueID = $object.attr('id');
        if (opt.type == "md") {
            $('#' + $uniqueID + '_edit').before($object);
            $('#' + $uniqueID + '_edit').remove();
            $object.show();
            $object.removeAttr('class');
            $object.removeAttr('placeholder');
            $object.removeAttr('name');
        } else {
            var $uniqueID = $object.attr('id');
           
            $object.show();
        }
    }

    function resize($object, params) {
        var opt = options($object);
        if (typeof params == "object") {
            if (!(params.width === undefined)) {
                opt.width = params.width;
            }
            if (!(params.width === undefined)) {
                opt.height = params.height;
            }
        }

        var $uniqueID = $object.attr('id');
        if (opt.type == "md") {
            if (opt.editor_ === undefined) {
                return;
            }

            opt.editor_.width(opt.width + "px");
            opt.editor_.height(opt.height + "px");
            //opt.editor_.resize(opt.width, opt.height);

            if (!opt.isEdit) {
                var view = $("#" + $uniqueID + "_edit2")
                if (view.length > 0) {
                    view.yqMDView("resize", {
                        "width": opt.width,
                        "height": opt.height
                    });
                }
            }
        } else {
            if (opt.types.length > 0) {
                $("#" + $uniqueID + "_div").css({
                    width: opt.width + 'px',
                    height: opt.height + 'px'
                });
            }
            if (!(opt.editor === undefined)) {
                opt.editor.setSize(opt.width + 'px', opt.height + 'px'); //设置代码框的长宽
            }
        }
    }

    function init_edit($object) {
        var opt = options($object);
        var $uniqueID = $object.attr('id');
        opt.modes = {
            html: {
                mode: "application/x-ejs",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/xml/xml.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/javascript/javascript.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/css/css.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/htmlmixed/htmlmixed.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/mode/multiplex.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/htmlembedded/htmlembedded.js", type: "js" }
                ]
            }, aspx: {
                mode: "application/x-ejs",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/xml/xml.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/javascript/javascript.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/css/css.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/htmlmixed/htmlmixed.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/mode/multiplex.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/htmlembedded/htmlembedded.js", type: "js" }
                ]
            }, js: {
                mode: "javascript",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/javascript/javascript.js", type: "js" },
                ]
            }, css: {
                mode: "css",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/css/css.js", type: "js" },
                ]
            }, txt: {
                mode: "textile",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/textile/textile.js", type: "js" }
                ]
            }, min: {
                mode: "textile",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/textile/textile.js", type: "js" }
                ]
            }, json: {
                mode: { name: "javascript", json: true },
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/mode/javascript/javascript.js", type: "js" },
                ]
            }, config: {
                mode: "xml",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/show-hint.css", type: "css" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/show-hint.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/xml-hint.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/xml/xml.js", type: "js" },
                ]
            }, xml: {
                mode: "xml",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/show-hint.css", type: "css" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/show-hint.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/xml-hint.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/xml/xml.js", type: "js" },
                ]
            }, sql: {
                mode: "text/x-mariadb",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/addon/edit/matchbrackets.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/sql/sql.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/show-hint.css", type: "css" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/show-hint.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/hint/sql-hint.js", type: "js" },
                ]
            }, python: {
                mode: {
                    name: "text/x-cython",
                    version: 2,
                    singleLineStringErrors: false
                },
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/lib/codemirror.css", type: "css" },
                    { url: "/scripts/editor.md/lib/codemirror/lib/codemirror.js", type: "js" },
                    { url: "/scripts/editor.md/lib/codemirror/addon/edit/matchbrackets.js", type: "css" },
                    { url: "/scripts/editor.md/lib/codemirror/mode/python/python.js", type: "js" }
                ]
            }
        };

        opt.themes_val = {
            eclipse: {
                theme: "eclipse",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/eclipse.css", type: "css" },
                ]
            }, light: {
                theme: "xq-light",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/xq-light.css", type: "css" },
                ]
            }, day: {
                theme: "3024-day",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/3024-day.css", type: "css" },
                ]
            }, night: {
                theme: "3024-night",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/3024-night.css", type: "css" },
                ]
            }, idea: {
                theme: "idea",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/idea.css", type: "css" },
                ]
            }, twilight: {
                theme: "twilight",
                jscss: [
                    { url: "/scripts/editor.md/lib/codemirror/theme/twilight.css", type: "css" },
                ]
            }
        }

        if (opt.type === null || opt.type == "") {
            opt.type = "text";
        }
        if (opt.types.length == 0) {
            opt.types.push(opt.type);
        }

        if (opt.types.length > 1) {
            $div = $('<div id="' + $uniqueID + '_div" style="position: relative;"></div>');
            var select_ = '<select class="selectmode" style="z-index: 99;position: absolute;right: 8px;width: 100px;border:1px solid rgb(239, 239, 239);font-size: small;">'
            for (let i = 0; i < opt.types.length; i++) {
                select_ += '<option value="' + opt.types[i] + '"' + (opt.type == opt.types[i] ? ' selected' : '') + '>' + opt.types[i] + '</option>';
            }
            select_ += '</select>';

            opt.$select = $(select_);
            $object.wrap($div);
            $object.before(opt.$select);

            $object.height(opt.height - 33);

            opt.$select.bind("change", function (event) {
                selectMode($object);
            });
        }
        opt.editor = CodeMirror.fromTextArea($object[0], {
            lineNumbers: true,
            matchBrackets: true,
            readOnly: !opt.isEdit,

            //代码折叠
            lineWrapping: true,
            foldGutter: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            autofocus: true,
        });

        if (!(opt.modes[opt.type] === undefined)) {
            $.yqLoadJsCss(opt.modes[opt.type].jscss, function () {
                opt.editor.setOption("mode", opt.modes[opt.type].mode);
            });
        }

        if (!(opt.themes_val[opt.theme] === undefined)) {
            $.yqLoadJsCss(opt.themes_val[opt.theme].jscss, function () {
                opt.editor.setOption("theme", opt.themes_val[opt.theme].theme);
            });
        }

        $object.next().css({
            "border": "1px solid #efefef",
            "font-size": opt.fontSize + "px",
            "width": $object.width(),
            "height": $object.height()
        });

        resize($object);
        opt.onload = false;

        $object.removeAttr("readonly");

        if (!(opt.value === undefined ||
            opt.value === null ||
            opt.value == "")) {
            setValue($object, opt.value);
        }
    }

    function init_edit_md($object) {
        var opt = options($object);
        var $uniqueID = $object.attr('id');
        $object.empty();

        var $div = $('<div id="' + $uniqueID + '_edit"></div>');
        $object.wrap($div);

        opt.editor = editormd($uniqueID + "_edit", {
            //width: opt.width,
            //height: opt.height,
            saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
            path: '/scripts/editor.md/lib/',
            toolbarIcons: function () {
                return [
                    "undo", "redo", "|",
                    "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
                    "h1", "h2", "h3", "h4", "|",
                    "list-ul", "list-ol", "hr", "|",
                    "link", "reference-link", "image_yq", "code", "preformatted-text", "code-block", "table", "html-entities", "pagebreak", "|",
                    "goto-line", "watch", "preview", "fullscreen", "clear", "search"
                ];
            },
            toolbarCustomIcons: {
                image_yq: '<a name="image_yq" title="添加图片" href="javascript:viod(0);"><i class="fa fa-picture-o"></i></a>'
            },

            onload: function () {
                $object.removeAttr("readonly");

                opt.editor_ = this;
                opt.onload = false;

                if (!(opt.data.code === undefined ||
                    opt.data.codee === null ||
                    opt.data.code == "")) {
                    setData($object, opt.data);
                } else if (!(opt.value === undefined ||
                    opt.value === null ||
                    opt.value == "")) {
                    setValue($object, opt.value);
                }

                $("[name=\"image_yq\"]").bind("click", function () {
                    openImageEdit($object);
                });

                isEdit($object, opt.isEdit);

                opt.editor_.width(opt.width + "px");
                opt.editor_.height(opt.height + "px");
            },
            onchange: function () {
                opt.onChange.call($object, this.getValue());
            }
        });

        $('#' + $uniqueID + '_edit').css({
            "width": $object.width(),
            "height": $object.height(),
            "margin": "0px",
            "z-index": 1
        });
    }

    //添加图片
    function openImageEdit($object) {
        var opt = options($object);
        var dialogContent = `
              <dic class="editormd-form">
                <label>图片地址</label>
                <input name="file-url" type="text">`
            + ((opt.storageType == 1 || opt.storageType == 2) ? `
            <div class="editormd-file-input">
            <input type="file" name="editormd-image-file" accept="image/*">
            <input type="submit" value="本地上传">
            </div>
        ` : '') + ` 
         <br>
            <label>图片描述</label>
            <input name="file-alt" type="text" value="">
            <br>
            <label>图片链接</label>
            <input name="file-link" type="text" value="http://">
            <br>
          </div>
            `;

        var settings = opt.editor.settings;
        var dialog = opt.editor.createDialog({
            title: "添加图片",
            width: (opt.storageType == 1 || opt.storageType == 2) ? 470 : 400,
            height: 254,
            name: "image",
            content: dialogContent,
            mask: settings.dialogShowMask,
            drag: settings.dialogDraggable,
            lockScreen: settings.dialogLockScreen,
            maskStyle: {
                opacity: settings.dialogMaskOpacity,
                backgroundColor: settings.dialogMaskBgColor
            },
            buttons: {
                enter: ["确定", function () {
                    var url = this.find("[name='file-url']").val();
                    var alt = this.find("[name='file-alt']").val();
                    var link = this.find("[name='file-link']").val();
                    var cursor = opt.editor.cm.getCursor();

                    if (url === "") {
                        alert("imageLang.imageURLEmpty");
                        return false;
                    }

                    var altAttr = (alt !== "") ? " \"" + alt + "\"" : "";

                    if (link === "" || link === "http://" || link === "https://") {
                        opt.editor.cm.replaceSelection("![" + alt + "](" + url + altAttr + ")");
                    }
                    else {
                        opt.editor.cm.replaceSelection("[![" + alt + "](" + url + altAttr + ")](" + link + altAttr + ")");
                    }

                    if (alt === "") {
                        opt.editor.cm.setCursor(cursor.line, cursor.ch + 2);
                    }

                    this.hide().lockScreen(false).hideMask();
                    this.remove();
                    return false;
                }],

                cancel: ["取消", function () {
                    this.hide().lockScreen(false).hideMask();
                    this.remove();
                    return false;
                }]
            }
        });

        opt.editor.dialogShowMask(dialog);
        opt.editor.dialogLockScreen();
        dialog.show();

        dialog.find("[type=\"text\"]").val("");
        dialog.find("[type=\"file\"]").val("");
        dialog.find("[name='file-link']").val("https://");

        if (!(opt.storageType == 1 || opt.storageType == 2)) {
            return;
        }

        var fileInput = dialog.find("[type=\"file\"]");
        fileInput.bind("change", function (event) {
            var files = event.target.files;
            var fileName = fileInput.val();
            var isImage = new RegExp("(\\.(" + settings.imageFormats.join("|") + "))$", "i"); // /(\.(webp|jpg|jpeg|gif|bmp|png))$/
            if (fileName === "") {
                alert("imageLang.uploadFileEmpty");
                return false;
            }

            if (!isImage.test(fileName)) {
                alert(imageLang.formatNotAllowed + settings.imageFormats.join(", "));
            }

            fileAction($object, files[0], function (fileurl, res) {
                dialog.find("[name='file-url']").val(fileurl);
                dialog.find("[name='file-alt']").val(res.title);
            });
        });
    }

    function fileAction($object, file, callback) {
        var opt = options($object);
        if (!opt.directup) {
            var blobUri = getFileUrl(file);
            opt.edit_files.push({ blobUri: blobUri, file: file })
            callback(blobUri, { title: file.name });

            return;
        }

        if (opt.storageType == 2 && opt.chunk) {
            $.yqFileChunkUpload(file, {
                ajaxUrl: '/_file.html',
                // sto_type: opt.storageType,     //1-数据库存储，2-外部存储
                sto_name: opt.storageName,     //外部存储库名
                // 上传完成
                success: function (res) {
                    if (res.error == 0) {
                        opt.html_files.push(res.file);
                        var f_url;
                        if (res.file.sto_type == 1) {
                            f_url = "!" + res.file.sto_name + "_" + res.file.sid;
                        } else if (res.file.sto_type == 2) {
                            f_url = "^" + res.file.sto_name + "_" + res.file.sid;
                        }
                        callback(f_url, { title: res.file.name });
                        $.yqMessager("success", "上传成功。");
                    } else {
                        $.yqMessager("error", res.info + "[" + res.error + "]");
                    }
                },
            })
        } else {
            $.yqFileUpload(file, {
                ajaxUrl: '/_file.html',
                sto_type: opt.storageType,     //1-数据库存储，2-外部存储
                sto_name: opt.storageName,     //外部存储库名
                // 上传完成
                success: function (res) {
                    if (res.error == 0) {
                        opt.html_files.push(res.file);
                        var f_url;
                        if (res.file.sto_type == 1) {
                            f_url = "!" + res.file.sto_name + "_" + res.file.sid;
                        } else if (res.file.sto_type == 2) {
                            f_url = "^" + res.file.sto_name + "_" + res.file.sid;
                        }
                        callback(f_url, { title: res.file.name });
                        $.yqMessager("success", "上传成功。");
                    } else {
                        //setData($object, null);
                        $.yqMessager("error", res.info + "[" + res.error + "]");
                    }
                },
            })
        }
    }

    /**
  * 从 file 域获取 本地图片 url
  */
    function getFileUrl(file) {
        var url;
        if (window.navigator.userAgent.indexOf("Chrome") >= 1 || window.navigator.userAgent.indexOf("Safari") >= 1) {
            url = window.webkitURL.createObjectURL(file);
        }
        else {
            url = window.URL.createObjectURL(file);
        }
        return url;
    }

    function setTheme($object, theme) {
        var opt = options($object);
        if (opt.type == "md") {
            if (opt.themes_val[theme] === undefined) {
                return;
            }
            opt.editor.setCodeMirrorTheme(opt.themes_val[theme].theme);
        } else {
            if (opt.themes_val[theme] === undefined) {
                return;
            }

            $.yqLoadJsCss(opt.themes_val[theme].jscss, function () {
                opt.editor.setOption("theme", opt.themes_val[theme].theme);
            });
        }
    }

    //正常编辑时
    function selectMode($object) {
        var opt = options($object);

        var name = opt.$select.val();
        opt.type = name;
        if (opt.modes[name] === undefined) {
            return;
        }
        $.yqLoadJsCss(opt.modes[name].jscss, function () {
            opt.editor.setOption("mode", opt.modes[name].mode);
        });

    }

    function setValue($object, value) {
        var opt = options($object);

        opt.value = value;

        if (!opt.onload) {
            setValueRun($object, value);
        }
        else {
            setTimeout(function () {
                setValue($object, value);
            }, 500);
        }
    }

    function setValueRun($object, value) {
        var opt = options($object);
        if (value === undefined || value == "") {
            value = null;
        }
        opt.value = value;
        if (opt.type == "md") {
            opt.editor.show();
            opt.editor.setValue(value === null ? "" : value); //添加值
            isEdit($object, opt.isEdit);

            if (opt.goDocEnd) {
                opt.editor.gotoLine("last");
            }
        } else {
            if (opt.types.length > 1) {
                opt.$select.val(opt.type);
            } else {
                if (!(opt.modes[opt.type] === undefined)) {
                    $.yqLoadJsCss(opt.modes[opt.type].jscss, function () {
                        opt.editor.setOption("mode", opt.modes[opt.type].mode);
                    });
                }
            }

            opt.editor.setValue(value === null ? "" : value); //添加值
            if (opt.goDocEnd) {
                CodeMirror.commands["goDocEnd"](opt.editor) //移动到文件尾部
            }
        }
    }

    function getValue($object) {
        var opt = options($object);

        if (opt.onload) {
            return opt.value;
        }

        if (opt.type == "md") {
            opt.value = opt.editor.getMarkdown();
        } else {
            opt.value = opt.editor.getValue("\n");
        }
        return opt.value;
    }

    function setData($object, data) {
        var opt = options($object);
        opt.data = data;
        if (!opt.onload) {
            setDataRun($object, data);
        }
        else {
            setTimeout(function () {
                setData($object, data);
            }, 500);
        }
    }

    function setDataRun($object, data) {
        var opt = options($object);
        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        else if (typeof data != "object") {
            data = null;
        }
        if (data === null) {
            data = { files: [], code: "" };
        }
        opt.data = data;
        //选择后，未上传文件列表
        if (data.edit_files === undefined) {
            opt.edit_files = [];
        } else {
            opt.edit_files = data.edit_files;
        }

        opt.html_files = data.files;     //原网页文件信息 + 已上传文件

        setValueRun($object, data.code);
    }

    function getData($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");

        if (opt.onload) {
            return opt.data;
        }

        if (opt.type != "md") {
            return { code: getValue($object) };
        }

        var data = { edit_files: [], files: [], code: "" };
        var code = getValue($object);

        //console.log("files", getImgs(code));
        var $imgs = getImgs(code);
        for (let i = 0; i < $imgs.length; i++) {
            var src = $imgs[i];
            if (src.substring(0, 5) == "blob:") {
                for (let j = 0; j < opt.edit_files.length; j++) {
                    if (src.indexOf(opt.edit_files[j].blobUri) != -1) {
                        data.edit_files.push(opt.edit_files[j]);
                    }
                }
            } else {
                var filename = src;
                if (filename.lastIndexOf("/") > 0) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length);
                }
                var sto_type = 3;
                var sto_name = "";
                var sid = "";
                if (filename.substring(0, 1) == "!") {
                    sto_type = 1;
                } else if (filename.substring(0, 1) == "@" || filename.substring(0, 1) == "^") {
                    sto_type = 2;
                }
                if (sto_type == 1 || sto_type == 2) {
                    var f_names = filename.substring(1, filename.length).split("_");
                    sto_name = f_names[0];
                    sid = f_names[1];
                    if (sid.indexOf(" ") > 0) {
                        sid = sid.substring(0, sid.indexOf(" "));
                    }
                    var has_dip = false;
                    for (let j = 0; j < opt.html_files.length; j++) {
                        if (sto_type == opt.html_files[j].sto_type &&
                            sto_name == opt.html_files[j].sto_name &&
                            sid.indexOf(opt.html_files[j].sid) != -1) {
                            var has_f = false;
                            for (let l = 0; l < data.files.length; l++) {
                                if (sto_type == data.files[l].sto_type &&
                                    sto_name == data.files[l].sto_name &&
                                    opt.html_files[j].sid == data.files[l].sid) {
                                    has_f = true;
                                }
                            }
                            if (!has_f) {
                                data.files.push(opt.html_files[j]);
                            }
                            has_dip = true;
                            break;
                        }
                    }

                    // type Field_File struct {
                    //     Sid         string `json:"sid" sql:"sid"`
                    //     StorageType int    `json:"sto_type" sql:"sto_type"`
                    //     StorageName string `json:"sto_name" sql:"sto_name"`
                    //     Name        string `json:"name" sql:"name"`
                    //     Size        int    `json:"size" sql:"size"`
                    //     Type        string `json:"type" sql:"type"`
                    //     //Finger      string `json:"finger" sql:"finger"`
                    // }

                    if (!has_dip) {
                        data.files.push({
                            sid: sid,
                            sto_type: sto_type,
                            sto_name: sto_name
                        });
                    }
                }
            }
        }

        data.code = code;

        return data;
    }


    function getImgs(str) {
        var files = [];
        try {
            let reg = /\]\((.*?)\)/g;

            let dd = str.match(reg);

            dd.map(item => {
                let temp = item.replace(/(.*)\)/, '$1');
                console.log('temp', temp);
                temp = temp.replace('](', '');
                temp = decodeURIComponent(temp);
                files.push(temp);
            });
        } catch {

        }
        return files;
    }

    function isEdit($object, tf) {
        var opt = options($object);
        opt.isEdit = tf;
        if (opt.type == "md") {
            var $uniqueID = $object.attr('id');
            if (tf) {
                var view = $("#" + $uniqueID + "_edit2")
                if (view.length > 0) {
                    view.yqMDView("destroy");
                    view.remove();
                }
                opt.editor.show();
            } else {
                opt.editor.hide();
                var view = $("#" + $uniqueID + "_edit2")
                if (view.length == 0) {
                    view = $('<div id="' + $uniqueID + '_edit2"></div>');
                    view.css({ position: "fixed", width: opt.width, height: opt.height });
                    $("#" + $uniqueID + "_edit").after(view);
                }

                view.yqMDView({
                    value: opt.value
                });
            }
        } else {
            if (!(opt.editor === undefined)) {
                opt.editor.setOption("readOnly", !tf);
            }
        }

        resize($object);
    }

    function setFontSize($object, size) {
        var opt = options($object);
        if (size) {
            opt.fontSize = size;
        }
        if (opt.type == "md") {
            var $uniqueID = $object.attr('id');
            $('#' + $uniqueID + '_edit').find(".CodeMirror").css({
                "font-size": opt.fontSize + "px"
            });
        } else {
            $object.next().css({ "font-size": opt.fontSize + "px" });
        }
    }

    function setType($object, value) {
        var opt = options($object);
        opt.type = value;

        if (opt.$select) {
            opt.$select.val(value);
            opt.$select.trigger('change');
        }
    }

    function getType($object) {
        var opt = options($object);
        return opt.type;
    }
})(jQuery);